// @ts-nocheck
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { DateRangePicker, MessagePlugin } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
// 是否正在刷新的标记
let isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
let requests = [];
interface Result {
  code: number;
  msg: string;
  data?: any;
  errors?: any;
  extras?: any;
  statusCode: number;
  succeeded: boolean;
  timestamp: number;
}
type PersonHeard = {
  'access-token': string;
  'x-access-token': string;
  'content-type': string;
  environment: string;
};
// 请求响应参数，包含data
interface ResultData<T = any> extends Result {
  data?: T;
}
const apiUrl = {};
if (import.meta.env.MODE === 'development') {
  //开发环境下的执行操作
  //生产环境下的执行操作
  apiUrl['file'] = '//t-file.api.jiyi.show/';
  apiUrl['message'] = '//t-message.api.jiyi.show/';
  apiUrl['sys'] = '//t-sys.api.jiyi.show/';
  apiUrl['api'] = '//t-api.jiyi.show/';
} else {
  //生产环境下的执行操作
  apiUrl['file'] = '//file.api.jiyi.show/';
  apiUrl['message'] = '//message.api.jiyi.show/';
  apiUrl['sys'] = '//sys.api.jiyi.show/';
  apiUrl['api'] = '//api.jiyi.show/';
}
const URL: string = 'https://cqshop.360daypay.com' //'https://cqshop.360daypay.com'
enum RequestEnums {
  TIMEOUT = 20000,
  OVERDUE = 401, // 登录失效
  FAIL = 999, // 请求失败
  SUCCESS = 200, // 请求成功
}
const config = {
  // 默认地址
  baseURL: URL as string,
  // 设置超时时间
  timeout: RequestEnums.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: false,
};

class RequestHttp {
  // 定义成员变量并指定类型
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config);
    /**
     * 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
     */

    this.service.interceptors.request.use(
      (config: any) => {

        var configs: AxiosRequestConfig = config;
        configs.baseURL = URL


        let SMSCode = configs.data?.HW_CE_SMSCode;
        // console.log(configs.data.HW_CE_SMSCode);
        return {
          ...configs,
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
            // 'Access-Control-Allow-Origin': '*',
            // Authorization: token,
            // 'X-Authorization': Xtoken, // 请求头中携带token信息
            // hwappkey: Hwkeys.HWAppKey, 
            // hwappsecret: Hwkeys.HWAppSecret,
            // hwappid: Hwkeys.HWAppId,
            // 'hwrequest-timestamp': Hwkeys.HWRequestTimeStamp,
            // 'hw-message-code': SMSCode,
          },
        };
      },
      (error: AxiosError) => {
        // 请求报错
        Promise.reject(error);
      },
    );
    /**
     * 响应拦截器
     * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */

    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data, config } = response; // 解构
        console.log(data)
        if (data.code !== 0) {
          // this.handleCode(data.statusCode, data.errors);
          Promise.reject(data);
          // return Promise.reject(data);
          MessagePlugin.error({ content: data.message });
        }
        // Promise.reject(data);
        // Promise.resolve(data); 

        return response.data
      },
      (error: AxiosError) => {
        const { response } = error;
        if (response) {
          Promise.reject(response);

        }

      },
    );
  }
  handleCode(code: number, err?: any): void {
    // let url = window.location.href;
    // let redirectUrl = 'http://wz.jiyi.show/#/login?redirect=' + url;
    // switch (code) {
    //   case 403:
    //     MessagePlugin.error('登录过期');
    //     removeAuthorization();
    //     router.push({ path: '/login' });
    //     // outLogin(redirectUrl);
    //     break;
    //   case 401:
    //     removeAuthorization();
    //     MessagePlugin.error('登录过期');
    //     router.push({ path: '/login' });
    //     // router.push({ path: '/login' });

    //     // outLogin(redirectUrl);
    //     break;

    //   default:
    //     if (typeof err === 'string') {
    //       MessagePlugin.error(err);
    //     } else {
    //       MessagePlugin.error(JSON.stringify(err));
    //     }
    //     break;
    // }
  }
  // 常用方法封装
  get<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.get(url, { params });
  }
  post<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.post(url, params);
  }
  patch<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.patch(url, params);
  }
  put<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.put(url, params);
  }
  delete<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.delete(url, { params });
  }
  deletes<T>(url: string, params?: any): Promise<ResultData<T>> {
    return this.service.delete(url, { data: params });
  }
}

// 导出一个实例对象
export default new RequestHttp(config);
